package cn.yangliu.config.custom;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yangliu.comm.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.Cleanup;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

/**
 * @author 杨柳
 * @date 2019-05-31
 */
public interface SecurityHandler {

    default void handle(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Exception e) throws IOException, ServletException {
      handle(request,response,status);
    }

    default void handle(HttpServletRequest request, HttpServletResponse response, HttpStatus status) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        @Cleanup PrintWriter writer = response.getWriter();
        String msg = "success";
        if (!Objects.equals(status,HttpStatus.OK)){
            msg = "faild";
        }
        JsonResult<Object> jsonResult = JsonResult.getInstance(status.value(),msg);
        String json = JSON.toJSONString(jsonResult);
        writer.println(json);
    }
}
